package route

import (
	"gitee.com/gitee-go/core/common"
	"gitee.com/gitee-go/core/model/pipeline"
	"gitee.com/gitee-go/core/models"
	"gitee.com/gitee-go/server/comm"
	"github.com/gin-gonic/gin"
	"strings"
)

type BadgeController struct{}

func (BadgeController) GetPath() string {
	return "/badge"
}
func (c *BadgeController) Routes(g gin.IRoutes) {
	g.GET("/pipe/*repo", c.svgBuild)
}
func (BadgeController) svgBuild(c *gin.Context) {
	pth := c.Param("repo")
	if pth == "" {
		c.String(500, "param err")
		return
	}
	pths := strings.Split(pth[1:], "/")
	ln := len(pths)
	if ln < 3 {
		c.String(500, "param err")
		return
	}
	repoPath := strings.Join(pths[:ln-2], "/")
	name := pths[ln-2]
	branch := pths[ln-1]
	if repoPath == "" || name == "" {
		c.String(500, "param err")
		return
	}
	if branch == "" {
		branch = "master"
	}
	pie := &pipeline.TPipeline{}
	// 连表查询,因为参数分别在两个表
	ok, _ := comm.DBMain.GetDB().SQL(`
		select pie.* from t_pipeline pie
		join t_repo rp on pie.repo_id=rp.id
		where rp.full_name=?
		and pie.name=?
	`, repoPath, name).Get(pie)
	if !ok {
		c.String(404, "not found pipeline")
		return
	}
	bd := &models.ShowPipelineVersion{}
	// 连表查询,参数分别在两个表
	ok, _ = comm.DBMain.GetDB().SQL(`
		select bd.status as build_status FROM t_pipeline_version pv
		left join t_build bd on bd.pipeline_version_id=pv.id
		where  pv.deleted !=1
		and pv.pipeline_id=?
		and pv.branch=?
		and (bd.status=? or bd.status=? or bd.status=?)
		order by bd.created DESC
	`, pie.Id, branch, common.BUILD_STATUS_OK, common.BUILD_STATUS_ERROR, common.BUILD_STATUS_CANCEL).Get(bd)
	if !ok {
		c.String(404, "not found pipeline")
		return
	}
	hls := svgPipeErr
	if bd.BuildStatus == common.BUILD_STATUS_OK {
		hls = svgPipeOK
	}
	c.Writer.Header().Set("Cache-Control", "no-cache")
	c.Data(200, "image/svg+xml", []byte(hls))
}
